<?php
/**
 * Description of PlayerForm
 *
 * @author Laszlo.Pokoradi
 */
class PlayerForm extends Model {
  const CURRENT_XPATH = "./current[1]";
  const TREND_XPATH = "./trend[1]";

  private $current;
  private $trend;
  private $db;

  public function __construct($database) {
    $this->db = $database;

    $this->current = "";
    $this->trend = 0;
  }

  public function loadFromNode(DOMElement $docNode) {
    $doc = $docNode->ownerDocument;

    $xPath = new DOMXPath($doc);

    $qResult = $xPath->query(PlayerForm::CURRENT_XPATH,$docNode);
    $this->current = $qResult->item(0)->nodeValue;

    $qResult = $xPath->query(PlayerForm::TREND_XPATH,$docNode);
    $this->trend = $qResult->item(0)->nodeValue;
  }

  public function toXHTML() {
    $xhtml = "<br/>{$this->current} form and {$this->trend} trend";

    return $xhtml;
  }

  public function insertNewToDB($playerId) {
    $this->db->set('playerId',$playerId);
    $this->db->set('currentForm',$this->current);
    $this->db->set('trend',$this->trend);

    $query = $this->db->insert('playerform');

    if (!$query) {
      log_message('error', 'Error during playerform inserttion!');
      return false;
    }

    return $this->db->insert_id();
  }

  public function amendOldInDB($formId) {
    $this->db->where('id',$formId);
    $query = $this->db->get('playerform');

    if (!$query) {
      log_message('error','Error during playerform amendment!');
    } else {
      $tRow = $query->row();
      $oldId = $tRow->id;
      $playerId = $tRow->playerId;

      if ($tRow->currentForm!=$this->current
          || $tRow->trend!=$this->trend) {
        $newId = $this->insertNewToDB($playerId);

        $this->db->set('playerId', $playerId);
        $this->db->set('table','playerform');
        $this->db->set('oldId',$oldId);
        $this->db->set('newId',$newId);
        $this->db->set('insertTime',date('Y-m-d H:i:s'));
        $query = $this->db->insert('playerhistory');

        if (!$query) {
          log_message('error','Playerform amend was unsuccesful!');
        } else {
          return $newId;
        }
      }
    }
    return $oldId;
  }

  public function loadFromDB($formId) {
    $this->db->where('id',$formId);
    $query = $this->db->get('playerform');

    if (!$query || $query->num_rows()==0) {
      log_message('error', 'PlayerForm ('.$formId.') not found in the database!');
    } else {
      $result = $query->row();

      $this->current = $result->currentForm;
      $this->trend= $result->trend;
    }
  }
}
?>
